Skip to main content

Singleton

Creating a singleton object to store global data

Create a class to store the singleton data and attach it to an object in the scene with 'DO NOT DESTROY ON LOAD' checked.

In your Java class, do the following:

public class Data extends Component {

private int value1 = 10;
private int value1 = 20;

public int getValue1() {
return this.value1;
}

public void setValue1(int value1) {
this.value1 = value1;
}

public int getValue2() {
return this.value2;
}

public void setValue2(int value2) {
this.value2 = value2;
}
}

In your other Java class, do the following:

public class YourClass extends Component {

@Singleton
private Data data;

@Override
public void start() {
Console.log("Value 1: " + data.getValue1() + "\n" + "Value 2: " + data.getValue2());
}

@Override
public void repeat() {

if (Input.getTouch(0).isDown()) {

data.setValue1(data.getValue1() + 1);
data.setValue2(data.getValue2() + 1);
Console.log("Value 1: " + data.getValue1() + "\n" + "Value 2: " + data.getValue2());
}
}
}